from aip import AipSpeech
from aip import AipNlp
import os,subprocess
from s5_tuling import to_tuling
from uuid import uuid4

""" 你的 APPID AK SK """
APP_ID = '16436279'
API_KEY = 'Y4A4TuCxAzrx6haB8PMuQRCP'
SECRET_KEY = 'TYGXDfVQvC4degzeZvZnYhAfx5ubq1y7'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
nlp_clinet = AipNlp(APP_ID, API_KEY, SECRET_KEY)


# 读取文件
def get_file_content(filePath):
	os.system(f"ffmpeg -y  -i {filePath}  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm")
	with open(f"{filePath}.pcm", 'rb') as fp:
		return fp.read()


# 识别本地文件
def audio2text(filename):
	res = client.asr(get_file_content(filename), 'pcm', 16000, {
		'dev_pid': 1536,
	})
	Q = res.get("result")[0]
	return Q

def my_nlp(Q):
	A = "我不知道你在说什么"

	nlp_simnet = nlp_clinet.simnet("你今年多大了",Q).get("score")
	print(nlp_simnet)
	if nlp_simnet >= 0.75 :
		A = "我今年999了，差一年就成精了"

	nlp_simnet = nlp_clinet.simnet("你的名字叫什么",Q).get("score")
	print(nlp_simnet)
	if nlp_simnet >= 0.75:
		A = "我的名字叫亚历山大点大傻逼点李"
		# A = "我的名字叫 application"

	if A == "我不知道你在说什么":
		A = to_tuling(Q)

	return A

def text2auido(A):
	result = client.synthesis(A, 'zh', 1, {
		"spd": 4,
		'vol': 10,
		"pit": 8,
		"per": 4
	})
	# print(result)
	# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
	filename = f"{uuid4()}.mp3"
	filepath = os.path.join("chat",filename)
	if not isinstance(result, dict):
		with open(filepath, 'wb') as f:
			f.write(result)

	return filename
